package com.dhu.cst.ningtianzhe181310419.test;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dhu.cst.ningtianzhe181310419.test.Json.UserInfo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.prefs.Preferences;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public String username;
    public boolean isLogin = false;
    public EditText userId,userPassWord;
    public ProgressBar progressBar;
    public TextView userName;
    SharedPreferences sharedPreferences,info;
    SharedPreferences.Editor editor,infoEditor;
    public boolean flag = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(!isLogin) {
            setContentView(R.layout.activity_login);
            this.getSupportActionBar().hide();
            getDongtai();
        }
        else {
            setContentView(R.layout.activity_main);
            this.getSupportActionBar().hide();
            userName = this.findViewById(R.id.userName);
            BottomNavigationView navView = findViewById(R.id.nav_view);
            // Passing each menu ID as a set of Ids because each
            // menu should be considered as top level destinations.
            AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                    R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications, R.id.navigation_friends, R.id.navigation_my)
                    .build();
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
            NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
            NavigationUI.setupWithNavController(navView, navController);
            initInfo();
            getDongtai();
            userName.setText(Info.name);
        }
    }
    public void topic(View view){
        Toast.makeText(this,"已点击话题按钮",Toast.LENGTH_SHORT).show();
        ImageButton button1 = this.findViewById(R.id.imageButton1);
        button1.setBackgroundColor(Color.GRAY);
    }
    public void search(View view){
        Toast.makeText(this,"已点击搜索按钮",Toast.LENGTH_SHORT).show();
        ImageButton button2 = this.findViewById(R.id.imageButton2);
        button2.setBackgroundColor(Color.GRAY);
    }
    public void message(View view){
        Toast.makeText(this,"已点击通知按钮",Toast.LENGTH_SHORT).show();
        ImageButton button3 = this.findViewById(R.id.imageButton3);
        button3.setBackgroundColor(Color.GRAY);
    }
    public void xunzhangonClick(View view){
        Toast.makeText(this,"已点击勋章按钮",Toast.LENGTH_SHORT).show();
    }
    //进入个人信息修改界面
    public void changePersonalData(View view){
        Intent intent = new Intent();
        intent.setClass(MainActivity.this,ShowActivity.class);
        MainActivity.this.startActivity(intent);
//
    }

    public void initInfo(){
        OkHttpClient okHttpClient = new OkHttpClient();
        final Gson gson = new Gson();
        String json = gson.toJson(username);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url("http://106.15.200.177:8081/api/contactInfo/selectAll")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"获取信息失败！",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String info = response.body().string();
                /*UserInfo userInfo = new UserInfo();
                userInfo = gson.fromJson()*/
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"获取信息成功！"+info,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public void register(View view){
        Intent intent = new Intent();
        intent.setClass(MainActivity.this,RegisterActivity.class);
        MainActivity.this.startActivity(intent);
    }

    public void login(View view){
        userId = this.findViewById(R.id.userId);
        userPassWord = this.findViewById(R.id.userPassword);
        progressBar = this.findViewById(R.id.progressBarLogin);
        progressBar.clearAnimation();
        progressBar.setVisibility(View.INVISIBLE);
        if(judgeLogin(userId.getText().toString(),userPassWord.getText().toString())){
            progressBar.setVisibility(View.VISIBLE);
            /*MainActivity.this.runOnUiThread(new Runnable() {
                @SuppressLint("WrongConstant")
                public void run() {
                    try {
                        Thread.sleep(1500);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });*/
            Toast.makeText(this,"登陆成功！",Toast.LENGTH_SHORT).show();
            username = userId.getText().toString();
            setContentView(R.layout.activity_main);
            this.getSupportActionBar().hide();
            BottomNavigationView navView = findViewById(R.id.nav_view);
            // Passing each menu ID as a set of Ids because each
            // menu should be considered as top level destinations.
            AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                    R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications, R.id.navigation_friends, R.id.navigation_my)
                    .build();
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
            NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
            NavigationUI.setupWithNavController(navView, navController);
        }
        else{
            Toast.makeText(this,"用户名或密码错误，请重新输入",Toast.LENGTH_SHORT).show();
        }
    }

    public boolean judgeLogin(String userName,String passWord){
        OkHttpClient okHttpClient = new OkHttpClient();
        String json = "{\n" +
                "  \"password\": \"" + userName + "\",\n" +
                "  \"role\": 0,\n" +
                "  \"username\": \"" + passWord + "\"\n" +
                "}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url("http://106.15.200.177:8081/api/users/register")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"响应失败！",Toast.LENGTH_SHORT).show();
                    }
                });
                flag = false;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"响应成功！",Toast.LENGTH_SHORT).show();
                    }
                });
                flag = true;
            }
        });
        if(flag = false)
            return false;
        else
            return true;
    }

    public void getDongtai(){
        //Toast.makeText(MainActivity.this,"开始获取动态，并没有bug！！！",Toast.LENGTH_SHORT).show();
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url("http://106.15.200.177:8081/api/topic/selectAll")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Info.dongtaiString = "error!";
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String s = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Info.dongtaiString = s;
                    }
                });
            }
        });
    }
}